﻿using System;
using System.Net;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SharpSvn;
using System.IO;
using System.Data.OleDb;
using System.Data.Linq;
using System.Data.EntityClient;
using System.Data.SQLite;
using System.Collections.Specialized;
using GestoreSuperProgetto.Model;

namespace GestoreSuperProgetto
{
    public partial class StartForm : Form
    {
        private string connString = "";
        private DbEntities manager = null;
        
        internal SvnClient _client = null;

        public StartForm()
        {
            InitializeComponent();

            // Specify the provider name, server and database.
            string providerName = "System.Data.SQLite";
                        

            // Initialize the connection string builder for the
            // underlying provider.
            System.Data.SQLite.SQLiteConnectionStringBuilder sqlBuilder =
                new SQLiteConnectionStringBuilder();
            
            // Set the properties for the data source.
            sqlBuilder.DataSource = GestoreSuperProgetto.Properties.Settings.Default.DbPath; //@"J:\TMP\Denis\svnclient\"+"SProjSvnDb.db";

            // Build the SqlConnection connection string.
            string providerString = sqlBuilder.ToString();

            // Initialize the EntityConnectionStringBuilder.
            EntityConnectionStringBuilder entityBuilder =
                new EntityConnectionStringBuilder();

            //Set the provider name.
            entityBuilder.Provider = providerName;

            // Set the provider-specific connection string.
            entityBuilder.ProviderConnectionString = providerString;

            // Set the Metadata location.
            entityBuilder.Metadata = @"res://*/Model.sprojsvn.csdl|
                            res://*/Model.sprojsvn.ssdl|
                            res://*/Model.sprojsvn.msl";



            manager = new DbEntities(entityBuilder.ToString());


            var count = (from lbl in manager.LABELS
                         where lbl.URL == "trunk"
                         select lbl).Count();

            if (count == 0 && manager.LABELS.Count() == 0)
            {
                manager.AddToLABELS(new LABEL() { 
                    NAME = "Sviluppo",
                });
            }
        }

        public DbEntities DataManager
        {
            get { return manager; }
        }
        
        private void Form1_Load(object sender, EventArgs e)
        {
            LoginAccess login = new LoginAccess();
            login.Owner = this;
            if (login.ShowDialog() == DialogResult.OK)
            {
                manager.ActiveUser = login.ActiveUser;
            }

            if (manager.ActiveUser != null)
            {
                manager.ActiveUser.PERMISSIONS.Load();
                var countAdminPrj = (from perm in manager.ActiveUser.PERMISSIONS
                                     where perm.PADMIN > 0
                                     select perm).Count();
                manageUsersBtn.Visible = true;

                if (manager.ActiveUser.ISADMIN == 0)
                    manageUsersBtn.Text = "Gestione Utente";

                //if (manager.ActiveUser.ISADMIN == 1 || countAdminPrj > 0)
                manageProjectsBtn.Visible = true;

                _client = new SvnClient();
                _client.Notify += new EventHandler<SvnNotifyEventArgs>(_client_Notify);
                _client.Progress += new EventHandler<SvnProgressEventArgs>(client_Progress);
                //progressBar.Visible = true;
                _client.Authentication.DefaultCredentials = new NetworkCredential(this.manager.ActiveUser.SVNUSER, USER.Decrypt(this.manager.ActiveUser.SVNPASSWORD));

                UpdateProjectList();
            }
            else
            {
                Close();
            }
            tabControl.TabPages.RemoveAt(1);
        }

        private void UpdateProjectList()
        {
            var sPrjs = (from sprj in manager.SUPERPROJECTS.Include("LABEL_SUPERPROJECTS").Include("LABEL_SUPERPROJECTS.SUPERPROJECT").Include("LABEL_SUPERPROJECTS.LABEL")
                         orderby sprj.NAME
                         select sprj).ToList();

            sPrjs = sPrjs.Where(ele => manager.ActiveUser.CheckPermission(ele.ID, TypePermission.Update)).ToList();

            var adminSPrjs = sPrjs.Where(ele => manager.ActiveUser.CheckPermission(ele.ID, TypePermission.Admin)).ToList();

            newLabelBtn.Enabled = adminSPrjs.Count > 0;

            List<LABEL_PROJECTS> spList = new List<LABEL_PROJECTS>();
            List<SUPERPROJECTS_INSTALLED> spInstalledList = new List<SUPERPROJECTS_INSTALLED>();

            foreach (SUPERPROJECTS_INSTALLED spInstalled in manager.ActiveUser.SUPERPROJECTS_INSTALLED.CreateSourceQuery().Include("LABEL_SUPERPROJECTS").Include("LABEL_SUPERPROJECTS.SUPERPROJECT").Include("LABEL_SUPERPROJECTS.LABEL").ToList())
            {
                if (spInstalled.SUPERPROJECTS_INSTALLED_PARENT == null)
                    if (spInstalled.LABEL_SUPERPROJECTS!= null && spInstalled.LABEL_SUPERPROJECTS.SUPERPROJECT != null)
                    {
                        // 04/10/2011 Denis. Controllo se il numero di Etichette installate per il progetto è lo stesso del numero totale di etichette del progetto allora lo elimino dalla lista
                        var countLabelForSPrj = spInstalled.LABEL_SUPERPROJECTS.SUPERPROJECT.LABEL_SUPERPROJECTS.Count;
                        var countInstalledLabelForSPrj = (from sprjInst in manager.ActiveUser.SUPERPROJECTS_INSTALLED
                                                          where sprjInst.LABEL_SUPERPROJECTS.ID_SUPERPROJECT == spInstalled.LABEL_SUPERPROJECTS.ID_SUPERPROJECT
                                                          select sprjInst).Count();
                        if (countLabelForSPrj == countInstalledLabelForSPrj)
                            sPrjs.Remove(spInstalled.LABEL_SUPERPROJECTS.SUPERPROJECT);

                        spInstalledList.Add(spInstalled);
                        //spInstalled.SUPERPROJECTS.PROJECTS.Load();
                        var prjList = (from lblPrj in spInstalled.LABEL_SUPERPROJECTS.LABEL_PROJECTS.CreateSourceQuery().Include("PROJECT").ToList()
                                       select lblPrj).ToList();
                        spList.AddRange(prjList);
                    }
            }
            projectsDataGridView.DataSource = spList;
            sUPERPROJECTS_INSTALLEDBindingSource.DataSource = spInstalledList;

            _isSortAscending = !_isSortAscending;
            projectsInstalledDataGridView_ColumnHeaderMouseClick(projectsInstalledDataGridView, new DataGridViewCellMouseEventArgs(_sortColumn == null ? 1 : _sortColumn.Index, 0, 0, 0, new MouseEventArgs(System.Windows.Forms.MouseButtons.None, 0, 0, 0, 0)));

            superProjCmb.DisplayMember = "Name";
            superProjCmb.ValueMember = "pippo";
            superProjCmb.DataSource = sPrjs;

            if (sPrjs.Count() == 0)
                groupBox.Enabled = false;
            else
                groupBox.Enabled = true;

            switchTagBtn.Enabled = upBtn.Enabled = false;
            stepIntoBtn.Enabled = !upBtn.Enabled;
        }

        StringCollection conflictedFile = new StringCollection();
        void _client_Notify(object sender, SvnNotifyEventArgs e)
        {
            if (e.ContentState == SvnNotifyState.Conflicted)
            {
                conflictedFile.Add(e.FullPath);
            }
            logTxt.Text = e.ContentState.ToString() + ": " +e.FullPath;
            Application.DoEvents();
        }

        private void StartForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            manager.Dispose();
        }

        private void manageProjectsBtn_Click(object sender, EventArgs e)
        {
            ProjectsManagment projectMan = new ProjectsManagment();
            projectMan.Owner = this;
            if (projectMan.ShowDialog() == DialogResult.OK)
            {
            }

            UpdateProjectList();
        }

        private void manageUsersBtn_Click(object sender, EventArgs e)
        {
            if (manager.ActiveUser.ISADMIN == 1)
            {
                UsersManagment userMan = new UsersManagment();
                userMan.Owner = this;
                if (userMan.ShowDialog() == DialogResult.OK)
                {
                }
            }
            else
            {
                UserManager userman = new UserManager();
                userman.Owner = this;
                userman.User = manager.ActiveUser;
                if (userman.ShowDialog() == DialogResult.OK)
                {
                    DataManager.SaveChanges();
                }
            }


            UpdateProjectList();
        }

        private void CheckoutSuperProject(LABEL_SUPERPROJECTS currentLabelSuperPrj, string defaultDir)
        {
            CheckoutSuperProject(currentLabelSuperPrj, defaultDir, null);
        }

        private void CheckoutSuperProject(LABEL_SUPERPROJECTS currentLabelSuperPrj, string defaultDir, SUPERPROJECTS_INSTALLED spiParent)
        {
            string rootDir = System.IO.Directory.GetDirectoryRoot(defaultDir);

            //Controllo e scarico le dipendenze
            var pippo = manager.PROJECTS;
            //var pippo = currentLabelSuperPrj.LABEL_PROJECTS.CreateSourceQuery().Include("PROJECT");
            var list = (from label_sproj in currentLabelSuperPrj.LABEL_SUPERPROJECTS_CHILD.CreateSourceQuery().Include("SUPERPROJECT").Include("LABEL_PROJECTS").Include("LABEL_PROJECTS.PROJECT").ToList()
                        from label_proj in label_sproj.LABEL_PROJECTS
                        select new { Label_Project = label_proj, Label_SuperProject = label_sproj });

            var list2 = (from lproj in currentLabelSuperPrj.LABEL_PROJECTS.CreateSourceQuery().Include("LABEL").Include("PROJECT").ToList()
                         select lproj);
            
            foreach (var lbl_prj in list2)
            {
                var tmpSpiParent = CheckoutProject(defaultDir, currentLabelSuperPrj, lbl_prj, tagsRadio.Checked, spiParent);
                if (spiParent == null)
                    spiParent = tmpSpiParent;
            }

            foreach (var obj in list)
            {
                CheckoutProject(defaultDir, obj.Label_SuperProject, obj.Label_Project, tagsRadio.Checked, spiParent);
            }

            
        }

        private SUPERPROJECTS_INSTALLED CheckoutProject(string defaultDir, LABEL_SUPERPROJECTS labelSuperProject, LABEL_PROJECTS lblproj, bool isTag, SUPERPROJECTS_INSTALLED parentInstalled)
        {
            string rootDir = System.IO.Directory.GetDirectoryRoot(defaultDir);
            bool ExistDir = true;
            string defaultDirSPrj = string.IsNullOrEmpty(labelSuperProject.SUPERPROJECT.DEFAULTDIRECTORY) ? "" : labelSuperProject.SUPERPROJECT.DEFAULTDIRECTORY;
            string projectDir = System.IO.Path.Combine(defaultDir, defaultDirSPrj);
            projectDir = System.IO.Path.Combine(projectDir, lblproj.PROJECT.NAME);
            string iterDir = rootDir;
            foreach (string dir in projectDir.Split('\\'))
            {
                if (dir + "\\" == rootDir)
                    continue;

                iterDir = System.IO.Path.Combine(iterDir, dir);

                if (!System.IO.Directory.Exists(iterDir))
                {
                    ExistDir = false;
                    System.IO.Directory.CreateDirectory(iterDir);
                }
            }
            manager.ActiveUser.SUPERPROJECTS_INSTALLED.Load();

            SUPERPROJECTS_INSTALLED spi2 = null;
            if (parentInstalled != null)
            {
                var pppp = (from spinst in manager.ActiveUser.SUPERPROJECTS_INSTALLED.CreateSourceQuery().Include("SUPERPROJECTS_INSTALLED_PARENT").Include("LABEL_SUPERPROJECTS")
                        where spinst.LABEL_SUPERPROJECTS.ID_LABEL == labelSuperProject.ID_LABEL &&
                             spinst.LABEL_SUPERPROJECTS.ID_SUPERPROJECT == labelSuperProject.ID_SUPERPROJECT &&
                             spinst.SUPERPROJECTS_INSTALLED_PARENT != null &&
                             spinst.SUPERPROJECTS_INSTALLED_PARENT.ID_SP_INSTALLED == parentInstalled.ID_SP_INSTALLED
                        select spinst).ToList();
                spi2 = pppp.FirstOrDefault();
            }
            else
                spi2 = (from spinst in manager.ActiveUser.SUPERPROJECTS_INSTALLED.CreateSourceQuery().Include("SUPERPROJECTS_INSTALLED_PARENT").Include("LABEL_SUPERPROJECTS")
                        where spinst.LABEL_SUPERPROJECTS.ID_LABEL == labelSuperProject.ID_LABEL &&
                             spinst.LABEL_SUPERPROJECTS.ID_SUPERPROJECT == labelSuperProject.ID_SUPERPROJECT
                        select spinst).FirstOrDefault();

            if (spi2 == null)
            {
                spi2 = new SUPERPROJECTS_INSTALLED();
                spi2.DATE_CREATED = DateTime.Now;
                spi2.DATE_UPDATED = spi2.DATE_CREATED;
                spi2.DIRECTORY = System.IO.Path.Combine(defaultDir, defaultDirSPrj);
                //spi2.IDSuperProject = superProject.ID;
                spi2.LABEL_SUPERPROJECTS = labelSuperProject;
                //spi2.IDUser = manager.ActiveUser.ID;
                spi2.USER = manager.ActiveUser;                
                spi2.SUPERPROJECTS_INSTALLED_PARENT = parentInstalled;

                this.DataManager.AddToSUPERPROJECTS_INSTALLED(spi2);

                //DataManager.SuperProjectsInStalled.InsertOnSubmit(spi2);
                DataManager.SaveChanges();
            }
            else
            {
                spi2.DATE_UPDATED = DateTime.Now;
                DataManager.SaveChanges();
            }            

            if (!ExistDir)
            {

                string url = lblproj.TagFullUrl.Replace("#", "");

                var arg = new SvnCheckOutArgs(){                    
                };

                List<string> filesList = new List<string>();
                
                if (!isTag)
                {
                    url = lblproj.BranchFullUrl.Replace("#", "");
                    
                    arg.Notify += (sender, args) =>
                    {
                        if (args.NodeKind == SvnNodeKind.File)
                            filesList.Add(args.FullPath);
                    };
                }

                _client.CheckOut(new SvnUriTarget(url), projectDir, arg);

                if (isTag)
                    foreach(var file in filesList)
                        File.SetAttributes(file, FileAttributes.ReadOnly);
            }
            else
                _client.Update(projectDir);

            return spi2;
        }

        private void addProjectBtn_Click(object sender, EventArgs e)
        {
            groupBox.Enabled = false;
            LABEL_SUPERPROJECTS currentLabelSuperPrj = (labelPrjCmb.SelectedItem as LABEL_SUPERPROJECTS);

            string defaultDir = destinationDirTxt.Text;
            //defaultDir = System.IO.Path.Combine(defaultDir, currentSuperPrj.Name);

            CheckoutSuperProject(currentLabelSuperPrj, defaultDir);

            logTxt.Text = "Operazione completata";

            //var tableSPI = DataManager.SUPERPROJECTS_INSTALLED;

            groupBox.Enabled = true;

            UpdateProjectList();
        }

        void client_Progress(object sender, SvnProgressEventArgs e)
        {
            //if (e.TotalProgress != -1)
            //{
            //    progressBar.Maximum = (int)e.TotalProgress;
            //    progressBar.Value = (int)e.Progress;
            //    //progressBar.Refresh();
            //    Application.DoEvents();
            //}
        }

        private void browseBtn_Click(object sender, EventArgs e)
        {
            string defaultDir = manager.ActiveUser.DEFAULTDIR;

            folderBrowserDialog.SelectedPath = defaultDir;
            if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
            {
                LABEL_SUPERPROJECTS currentLabelSuperPrj = (labelPrjCmb.SelectedItem as LABEL_SUPERPROJECTS);
                destinationDirTxt.Text = Path.Combine(folderBrowserDialog.SelectedPath, currentLabelSuperPrj.LABEL.NAME);                
            }
        }

        private void superProjCmb_SelectedIndexChanged(object sender, EventArgs e)
        {
            string defaultDir = manager.ActiveUser.DEFAULTDIR;

            SUPERPROJECT currentSuperPrj = (superProjCmb.SelectedItem as SUPERPROJECT);

            //currentSuperPrj.LABEL_SUPERPROJECTS.Load();

            //currentSuperPrj.LABEL_SUPERPROJECTS.Load();

            var lblSPrjs = (from lblSPrj1 in currentSuperPrj.LABEL_SUPERPROJECTS
                          select lblSPrj1 );

            lblSPrjs = lblSPrjs.Where(lblSPrj =>
            {
                var countInstall = (from sinstall in manager.ActiveUser.SUPERPROJECTS_INSTALLED
                                    where sinstall.LABEL_SUPERPROJECTS.ID_LABEL == lblSPrj.ID_LABEL &&
                                          sinstall.LABEL_SUPERPROJECTS.ID_SUPERPROJECT == lblSPrj.ID_SUPERPROJECT
                                    select sinstall).Count();

                return countInstall ==0;
            });

            labelPrjCmb.DataSource = lblSPrjs.ToList();

            browseBtn.Enabled = !(lblSPrjs.Count() == 0);
            labelPrjCmb.Enabled = !(lblSPrjs.Count() == 0);
            addProjectBtn.Enabled = !(lblSPrjs.Count() == 0);
        }

        private void projectsInstalledDataGridView_SelectionChanged(object sender, EventArgs e)
        {
            if (projectsInstalledDataGridView.SelectedRows.Count > 0)
            {
                var pInstalled = projectsInstalledDataGridView.SelectedRows[0].DataBoundItem as SUPERPROJECTS_INSTALLED;

                updateProjectBtn.Enabled = manager.ActiveUser.CheckPermission(pInstalled.LABEL_SUPERPROJECTS.ID_SUPERPROJECT, TypePermission.Update);
                delProjBtn.Enabled = true;
                commitProjBtn.Enabled = manager.ActiveUser.CheckPermission(pInstalled.LABEL_SUPERPROJECTS.ID_SUPERPROJECT, TypePermission.Commit);
            }
            else
            {
                updateProjectBtn.Enabled = false;
                delProjBtn.Enabled = false;
                commitProjBtn.Enabled = false;
            }
        }

        private void updateProjectBtn_Click(object sender, EventArgs e)
        {
            if (tabControl.SelectedIndex == 0)
            {
                Action<SUPERPROJECTS_INSTALLED> updateFn = delegate(SUPERPROJECTS_INSTALLED spInstalled) {

                    var listProj = (from lblproj in spInstalled.LABEL_SUPERPROJECTS.LABEL_PROJECTS.CreateSourceQuery().Include("PROJECT").Include("LABEL").ToList()
                                    orderby lblproj.PROJECT.NAME
                                    select lblproj).ToList();

                    foreach (LABEL_PROJECTS proj in listProj)
                    {
                        if (System.IO.Directory.Exists(System.IO.Path.Combine(spInstalled.DIRECTORY, proj.PROJECT.NAME)))
                            _client.Update(System.IO.Path.Combine(spInstalled.DIRECTORY, proj.PROJECT.NAME));
                        else
                        {
                            CheckoutProject(System.IO.Path.GetDirectoryName(spInstalled.DIRECTORY), spInstalled.LABEL_SUPERPROJECTS, proj, false, null);
                        }
                    }

                    spInstalled.DATE_UPDATED = DateTime.Now;
                };

                foreach (DataGridViewRow row in projectsInstalledDataGridView.SelectedRows)
                {
                    SUPERPROJECTS_INSTALLED spInstalled = (row.DataBoundItem as SUPERPROJECTS_INSTALLED);

                    //var listProj = (from sProjS in DataManager.SuperProjectsProjects
                    //                where sProjS.IDSuperProject == spInstalled.IDSuperProject
                    //                join proj in DataManager.Projects on sProjS.IDProject equals proj.ID
                    //                orderby proj.Name
                    //                select proj);
                    updateFn(spInstalled);

                    var listsProj = (from lblsproj in spInstalled.LABEL_SUPERPROJECTS.LABEL_SUPERPROJECTS_CHILD.CreateSourceQuery().Include("LABEL_PROJECTS").ToList()
                                         //.Include("PROJECT").Include("LABEL").ToList()
                                    orderby lblsproj.SuperProjectLabelName
                                    select lblsproj).ToList();                    

                    foreach (LABEL_SUPERPROJECTS sproj in listsProj)
                    {
                        SUPERPROJECTS_INSTALLED spInstalledChild = (from spinst in manager.ActiveUser.SUPERPROJECTS_INSTALLED
                                                                    where spinst.LABEL_SUPERPROJECTS.ID_LABEL == sproj.ID_LABEL &&
                                                 spinst.LABEL_SUPERPROJECTS.ID_SUPERPROJECT == sproj.ID_SUPERPROJECT
                                                                    select spinst).FirstOrDefault();

                        // Denis 23/11/12. Dipendenza già installata faccio aggiornamento
                        if (spInstalledChild != null)
                        {
                            updateFn(spInstalledChild);
                        }
                        else {
                            CheckoutSuperProject(sproj, System.IO.Path.GetDirectoryName(spInstalled.DIRECTORY), spInstalled);
                        }
                    }

                    

                    manager.SaveChanges();

                    if (conflictedFile.Count > 0)
                    {
                        MessageBox.Show("Ci sono uno o più file in conflitto", "SvnClient", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    }

                    logTxt.Text = "Aggiornamento Completato";
                }
            }
            else if (tabControl.SelectedIndex == 1)
            {
                foreach (DataGridViewRow row in projectsDataGridView.SelectedRows)
                {
                    LABEL_PROJECTS selproj = (row.DataBoundItem as LABEL_PROJECTS);
                    selproj.LABEL_SUPERPROJECTS.Load();

                    manager.ActiveUser.SUPERPROJECTS_INSTALLED.Load();

                    foreach (LABEL_SUPERPROJECTS sproj in selproj.LABEL_SUPERPROJECTS)
                    {
                        var spInstalled = (from spinst in manager.ActiveUser.SUPERPROJECTS_INSTALLED
                                           where spinst.LABEL_SUPERPROJECTS.ID_LABEL == sproj.ID_LABEL &&
                                                 spinst.LABEL_SUPERPROJECTS.ID_SUPERPROJECT == sproj.ID_SUPERPROJECT
                                           select spinst).FirstOrDefault();

                        if (spInstalled != null && System.IO.Directory.Exists(System.IO.Path.Combine(spInstalled.DIRECTORY, selproj.PROJECT.NAME)))
                            _client.Update(System.IO.Path.Combine(spInstalled.DIRECTORY, selproj.PROJECT.NAME));
                    }
                }
            }

            UpdateProjectList();
        }

        private void delProjBtn_Click(object sender, EventArgs e)
        {
            foreach (DataGridViewRow row in projectsInstalledDataGridView.SelectedRows)
            {
                SUPERPROJECTS_INSTALLED spInstalled = (row.DataBoundItem as SUPERPROJECTS_INSTALLED);

                //manager.SuperProjectsInStalled.DeleteOnSubmit(spInstalled);

                if (System.IO.Directory.Exists(spInstalled.DIRECTORY))
                {
                    logTxt.Text = "Ricordarsi di cancellare la cartella";
                }

                manager.DeleteObject(spInstalled);

                manager.SaveChanges();
            }

            UpdateProjectList();
        }

        private void commitProjBtn_Click(object sender, EventArgs e)
        {
            if (tabControl.SelectedIndex == 0)
            {
                foreach (DataGridViewRow row in projectsInstalledDataGridView.SelectedRows)
                {
                    SUPERPROJECTS_INSTALLED spInstalled = (row.DataBoundItem as SUPERPROJECTS_INSTALLED);

                    //var listProj = (from sProjS in DataManager.SuperProjectsProjects
                    //                where sProjS.IDSuperProject == spInstalled.IDSuperProject
                    //                join proj in DataManager.Projects on sProjS.IDProject equals proj.ID
                    //                orderby proj.Name
                    //                select proj);

                    var listProj = (from lblProj in spInstalled.LABEL_SUPERPROJECTS.LABEL_PROJECTS
                                    let proj = lblProj.PROJECT
                                    orderby proj.NAME
                                    select proj);

                    SelectionReleaseFileFrom selectionDlg = new SelectionReleaseFileFrom();

                    foreach (PROJECT proj in listProj)
                    {
                        if (System.IO.Directory.Exists(System.IO.Path.Combine(spInstalled.DIRECTORY, proj.NAME)))
                        {
                            var args = new SvnStatusArgs()
                            {
                                Depth = SvnDepth.Infinity,
                                RetrieveRemoteStatus = true,
                                RetrieveAllEntries = true
                            };

                            _client.Status(System.IO.Path.Combine(spInstalled.DIRECTORY, proj.NAME), args, selectionDlg.ReciveStatusFile);
                        }
                    }
                    //var args = new SvnStatusArgs()
                    //       {
                    //           Depth = SvnDepth.Infinity,
                    //           RetrieveRemoteStatus = true,
                    //           RetrieveAllEntries = true
                    //       };
                    //_client.Status(@"C:\Sviluppo\Welding Book Test\", args, selectionDlg.ReciveStatusFile);
                    selectionDlg.ClientSvn = _client;
                    selectionDlg.ShowDialog();

                    spInstalled.DATE_UPDATED = DateTime.Now;

                    manager.SaveChanges();
                }
            }
        }

        private void tabControl_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tabControl.SelectedIndex == 1)
            {
                delProjBtn.Enabled = false;
                commitProjBtn.Enabled = false;
            }
            else
            {
                delProjBtn.Enabled = true;
                commitProjBtn.Enabled = true;
            }
        }

        public void CopyAll(DirectoryInfo source, DirectoryInfo target)
        {
            // Check if the target directory exists, if not, create it.
            if (Directory.Exists(target.FullName) == false)
            {
                Directory.CreateDirectory(target.FullName);
            }

            // Copy each file into it’s new directory.
            foreach (FileInfo fi in source.GetFiles())
            {
                //Console.WriteLine(@”Copying {0}\{1}”, target.FullName, fi.Name);
                fi.CopyTo(Path.Combine(target.ToString(), fi.Name), true);
            }

            // Copy each subdirectory using recursion.
            foreach (DirectoryInfo diSourceSubDir in source.GetDirectories())
            {
                DirectoryInfo nextTargetSubDir =
                    target.CreateSubdirectory(diSourceSubDir.Name);
                CopyAll(diSourceSubDir, nextTargetSubDir);
            }
        }

        private void newProjectBtn_Click(object sender, EventArgs e)
        {
            
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            LABEL_SUPERPROJECTS currentLabelSuperPrj = (labelPrjCmb.SelectedItem as LABEL_SUPERPROJECTS);            
            groupBox1.Enabled = !(currentLabelSuperPrj.ID_LABEL == 1);

            string defaultDir = manager.ActiveUser.DEFAULTDIR;

            destinationDirTxt.Text = Path.Combine(defaultDir, currentLabelSuperPrj.LABEL.NAME);
        }

        private void projectsInstalledDataGridView_SortCompare(object sender, DataGridViewSortCompareEventArgs e)
        {
        }

        private void newLabelBtn_Click(object sender, EventArgs e)
        {
            LabelManagment labelMan = new LabelManagment(_client);
            labelMan.Owner = this;
            if (labelMan.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                UpdateProjectList();
            }
        }

        private void aggiornaToolStripMenuItem_Click(object sender, EventArgs e)
        {
            updateProjectBtn_Click(sender, e);
        }

        private void cancellaProgettoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            delProjBtn_Click(sender, e);
        }

        DataGridViewColumn _sortColumn = null;
        bool _isSortAscending = false;
        private void projectsInstalledDataGridView_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            DataGridViewColumn column = projectsInstalledDataGridView.Columns[e.ColumnIndex];

            _isSortAscending = (_sortColumn == null ? false : _sortColumn.Index == column.Index ? !_isSortAscending : _isSortAscending);
            
            List<SUPERPROJECTS_INSTALLED> listvalue = null;
            if(_isSortAscending)
                listvalue = (from ele in (sUPERPROJECTS_INSTALLEDBindingSource.DataSource as List<SUPERPROJECTS_INSTALLED>)
             select ele).OrderBy( ele =>{
                 var prop = ele.GetType().GetProperty(column.DataPropertyName, System.Reflection.BindingFlags.Instance| System.Reflection.BindingFlags.Public);
                 if (prop!=null)
                    return prop.GetValue(ele, null).ToString();
                 return "";
             }).ToList();
            else
                listvalue = (from ele in (sUPERPROJECTS_INSTALLEDBindingSource.DataSource as List<SUPERPROJECTS_INSTALLED>)
                             select ele).OrderByDescending(ele =>
                             {
                                 var prop = ele.GetType().GetProperty(column.DataPropertyName, System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
                                 if (prop != null)
                                     return prop.GetValue(ele, null).ToString();
                                 return "";
                             }).ToList();

            sUPERPROJECTS_INSTALLEDBindingSource.DataSource = listvalue;

            if (_sortColumn != null) _sortColumn.HeaderCell.SortGlyphDirection = SortOrder.None;
            column.HeaderCell.SortGlyphDirection = _isSortAscending ? SortOrder.Ascending : SortOrder.Descending;
            _sortColumn = column;
        }

        private void stepIntoBtn_Click(object sender, EventArgs e)
        {
            stepIntoBtn.Enabled = false;
            upBtn.Enabled = true;
            switchTagBtn.Enabled = upBtn.Enabled;

            SUPERPROJECTS_INSTALLED spInstalled = (projectsInstalledDataGridView.SelectedRows[0].DataBoundItem as SUPERPROJECTS_INSTALLED);
            updateStepIntoSPrj(spInstalled);
        }

        private void updateStepIntoSPrj(SUPERPROJECTS_INSTALLED spInstalled)
        {
            var listsProj = (from lblsproj in manager.ActiveUser.SUPERPROJECTS_INSTALLED.CreateSourceQuery().Include("LABEL_SUPERPROJECTS").Include("LABEL_SUPERPROJECTS.SUPERPROJECT").Include("LABEL_SUPERPROJECTS.LABEL").ToList()
                             where lblsproj.SUPERPROJECTS_INSTALLED_PARENT!=null && lblsproj.SUPERPROJECTS_INSTALLED_PARENT.ID_SP_INSTALLED == spInstalled.ID_SP_INSTALLED
                             orderby lblsproj.SuperProjectLabelName
                             select lblsproj).ToList();

            sUPERPROJECTS_INSTALLEDBindingSource.DataSource = null;
            sUPERPROJECTS_INSTALLEDBindingSource.DataSource = listsProj;
        }

        private void upBtn_Click(object sender, EventArgs e)
        {
            UpdateProjectList();
        }

        private void projectsInstalledDataGridView_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (stepIntoBtn.Enabled)
                stepIntoBtn_Click(null, EventArgs.Empty);
        }

        private void projectsInstalledDataGridView_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            var pippo = projectsInstalledDataGridView.HitTest(e.X, e.Y);
            if (pippo.Type == DataGridViewHitTestType.None && upBtn.Enabled)
            {
                upBtn_Click(null, EventArgs.Empty);
            }
        }

        ContextMenuStrip contextBtn = new System.Windows.Forms.ContextMenuStrip();

        private void switchTagBtn_Click(object sender, EventArgs e)
        {
            SUPERPROJECTS_INSTALLED spInstalled = (projectsInstalledDataGridView.SelectedRows[0].DataBoundItem as SUPERPROJECTS_INSTALLED);

            foreach (ToolStripMenuItem item in contextMenuStrip1.Items)
                item.Click -= switchPrj;

            contextBtn.Items.Clear();

            var items = FillContext(spInstalled);

            if (items != null)
                contextBtn.Items.AddRange(items);

            contextBtn.Show(switchTagBtn, new Point(0, switchTagBtn.Height));
        }

        private void switchPrj(object sender, EventArgs e)
        {
            ToolStripMenuItem item = sender as ToolStripMenuItem;
            var lblSPrj = item.Tag as LABEL_SUPERPROJECTS;

            SUPERPROJECTS_INSTALLED spInstalled = (projectsInstalledDataGridView.SelectedRows[0].DataBoundItem as SUPERPROJECTS_INSTALLED);

            logTxt.Text = "Cancellazione directory....";
            if (System.IO.Directory.Exists(spInstalled.DIRECTORY))
            {
                System.IO.Directory.Delete(spInstalled.DIRECTORY, true);
            }
            logTxt.Text = "Download nuova versione....";

            spInstalled.SUPERPROJECTS_INSTALLED_PARENT.Load();
            var parent = spInstalled.SUPERPROJECTS_INSTALLED_PARENT;

            manager.DeleteObject(spInstalled);

            manager.SaveChanges();

            upBtn_Click(sender, e);
            CheckoutSuperProject(lblSPrj, System.IO.Path.GetDirectoryName(spInstalled.DIRECTORY), parent);
            logTxt.Text = "Aggiornamento Completato";
        }

        private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
        {
            switchEtichettaToolStripMenuItem.Visible = switchTagBtn.Enabled;
            if (switchTagBtn.Enabled)
            {
                SUPERPROJECTS_INSTALLED spInstalled = (projectsInstalledDataGridView.SelectedRows[0].DataBoundItem as SUPERPROJECTS_INSTALLED);
                
                foreach (ToolStripMenuItem item in switchEtichettaToolStripMenuItem.DropDownItems)
                    item.Click -= switchPrj;

                switchEtichettaToolStripMenuItem.DropDownItems.Clear();

                var items = FillContext(spInstalled);

                if (items != null)
                    switchEtichettaToolStripMenuItem.DropDownItems.AddRange(items);
                else
                    switchEtichettaToolStripMenuItem.Visible = false;
            }
        }

        private ToolStripMenuItem[] FillContext(SUPERPROJECTS_INSTALLED spInstalled)
        {
            List<ToolStripMenuItem> listItems = new List<ToolStripMenuItem>();
            var lblSPrjs = (from lblSPrj in manager.LABEL_SUPERPROJECTS
                            where lblSPrj.ID_SUPERPROJECT == spInstalled.LABEL_SUPERPROJECTS.ID_SUPERPROJECT &&
             lblSPrj.ID_LABEL != spInstalled.LABEL_SUPERPROJECTS.ID_LABEL
                            select lblSPrj).ToList();

            if (lblSPrjs.Count() > 0)
            {
                foreach (var lblSPrj in lblSPrjs)
                {

                    var item = new ToolStripMenuItem(lblSPrj.LABEL.NAME, GestoreSuperProgetto.Properties.Resources.label)
                        {
                            Tag = lblSPrj
                        };

                    item.Click += switchPrj;
                    listItems.Add(item);
                }
            }
            else
                return null;

            return listItems.ToArray();
        }
    }
}

